//

//导入axios
import axios from 'axios';
import { ElMessage } from 'element-plus'
import { useTokenStore } from '@/stores/token';

// const baseURL = 'http://localhost:8080';
const baseURL = '/api';
const instance = axios.create({
    baseURL: baseURL
});
//添加请求拦截器
instance.interceptors.request.use(
    (config) => {
        // 请求前的回调
        //添加token
        const tokenStore = useTokenStore();
        console.log('request中TokenStore:'+tokenStore.token);
        // if(tokenStore.token){
        //     console.log('测试token是否在请求头中')
        //     config.headers.Authorization = `Bearer ${tokenStore.token}`;

        //     // config.headers.Authorization = tokenStore;
        // }
        if (tokenStore.token) {
            config.headers.Authorization = tokenStore.token;
        }
        // console.log(config.headers.Authorization);
        return config;
    },
    (err) => {
        return Promise.reject(err);
    }
)

// import { useRouter } from 'vue-router';
// const router = useRouter();

import router from '@/router';
//添加响应拦截器
instance.interceptors.response.use(
    result => {
        console.log(result.data);
        //判断业务状态码
        if (result.data.code === 0) {
            return result.data;
        }
        //操作失败
        // alert(result.data.msg?result.data.msg:'服务异常');
        ElMessage.error(result.data.message ? result.data.message : '服务异常');
        //将异步操作状态转换为失败
        return Promise.reject(result.data);
    },
    err => {
        // 判断响应状态码，如果为401，则证明未登录，提示请登录后并跳转登录页面
        if (err.response.status === 401) {
            ElMessage.error('未登录,请先登录');
            router.push('/login')
        } else {
            ElMessage.error('服务异常');
        }

        return Promise.reject(err);//从异步的状态变成失败的状态
    }
)

export default instance;